// pages/handWriting.js
/**
 * 签名界面
 */
const app = getApp()
const httpsUrl = app.httpsPrefix;

const constLineWidth = 8;

const {$Message} = require('../../dist/base/index');
const {$Toast} = require('../../dist/base/index');

Page({
    data: {
        width: 0, height: 0,
        id: 'handWriting',
        lastLoc: {x: 0, y: 0},
        isOnMoveDown: false,
        lastTimestamp: 0,
        lastLineWidth: constLineWidth
    },
    mouseDown() {
        this.setData({
            isOnMoveDown: true
        })
    },
    uploadScaleStart(e) {
        console.log(e)
        let [touch0, touch1] = e.touches
        let curLoc = {
            x: touch0.x,
            y: touch0.y
        };

        this.setData({
            lastLoc: curLoc,
            lastTimestamp: new Date().getTime(),
            isOnMoveDown: true,
            lastLineWidth: constLineWidth
        })
    },
    uploadScaleMove(e) {
        // console.log(e)
        let [touch0, touch1] = e.changedTouches
        //draw
        let isOnMoveDown = this.data.isOnMoveDown;
        if (isOnMoveDown) {
            let ctx = this.data.ctx;

            let curLoc = touch0;
            let lastLoc = this.data.lastLoc;
            let currTimestamp = new Date().getTime();
            ctx.beginPath()
            ctx.moveTo(lastLoc.x, lastLoc.y)
            ctx.lineTo(curLoc.x, curLoc.y)
            ctx.setStrokeStyle('black')
            ctx.setLineCap('round')
            ctx.setLineJoin('round')
            ctx.setLineWidth(constLineWidth)

            ctx.stroke()
            ctx.draw(true)
            //console.log(touch0, touch1);
            this.setData({
                lastLoc: curLoc,
                lastTimestamp: currTimestamp,
                lastLineWidth: constLineWidth
            })
        }
    },
    retDraw: function () {
        this.setData({lastTimestamp: 0});
        this.data.ctx.clearRect(0, 0, 700, 730)
        this.data.ctx.draw()
        //this.data.ctx.restore()
        //this.drawBg()
    },

    calcDistance: function (loc1, loc2) {
        return Math.sqrt((loc1.x - loc2.y) * (loc1.x - loc2.y) + (loc1.y - loc2.y) * (loc1.y - loc2.y))
    },
    uploadScaleEnd: function () {
        this.setData({
            lastLineWidth: constLineWidth,
            lastTimestamp: new Date().getTime()
        })
    },
    onLoad: function (options) {
        //this.drawBg()
        this.getSysInfo();
        let id = this.data.id;
        let ctx = wx.createCanvasContext(id);
        this.setData({
            ctx: ctx
        })
    },
    getSysInfo: function () {
        let that = this;
        wx.getSystemInfo({
            success: function (res) {
                let pix = res.pixelRatio;
                that.setData({
                    width: res.windowWidth * pix,
                    height: res.windowHeight * pix
                })
            }
        })
    },

    /**
     * 可爱的分割线 - -，以上部分是书写板的逻辑，以下是上传手写图片的逻辑
     */
    /**------------------------------------------------------------------------------------------------**/
    subCanvas: function () {

        //未书写，弹出提示
        if (this.data.lastTimestamp === 0) {

            $Toast({
                content: '签名不得为空',
                type: 'warning'
            });
            return
        }

        $Toast({
            mask: false,
            content: '生成签名中..',
            type: 'loading'
        });

        this.createHandWritePic()

    },
    createHandWritePic() {
        //生成手写图片，并上传
        wx.canvasToTempFilePath({
            canvasId: 'handWriting',
            destWidth: 48,
            destHeight: 48 * this.data.height / this.data.width,
            success:
                (res) => {
                    this.doUpload(res)
                }
        })
    },
    doUpload: function (res) {
        let order = wx.getStorageSync("order")

        let account = wx.getStorageSync("username")

        var timestamp2 = (new Date()).valueOf();
        wx.uploadFile({
            url: httpsUrl, //接口地址
            filePath: res.tempFilePath,
            name: 'file',
            formData: {
                account:account,
                query: 'mp_uploadsign',
                单号: order,
                compress_name: account + '_' + order + '_' + timestamp2,
                compress_path: 'mp_sign'
            },
            success: ({data}) => {
                data = JSON.parse(data)
                $Toast.hide()
                if (data.flag === '0') {
                } else {
                    let signed = data.message
                    data = data.data[0].data
                    var array = wx.base64ToArrayBuffer(data);
                    var base64 = wx.arrayBufferToBase64(array);
                    wx.navigateTo({
                        url: '../signedpreview/signedpreview?base='+base64+'&signed='+signed
                    })
                }
            },
            fail: function (res) {
                $Toast.hide()

                $Toast({
                    content: '网络错误',
                    type: 'error'
                });

            }
        });
    }
})
